<template>
  <view class="user">
    <view
      class="nav"
      :style="{
        paddingTop: statusBarHeight + 'px',
        background: `rgba(0,0,0,${opacity})`,
      }"
    >
      <view class="nav-head">
        <image
          v-if="asyncImgs"
          :src="asyncImgs.common.back"
          mode="widthFix"
          @click="$utils.goBack()"
        />
      </view>
    </view>

    <template>
      <pageHeader
        :isUser="isUser"
        :isLike="isLike"
        :userInfo="userInfo"
        @follow="follow"
        :getSetting="getSetting"
      >
      </pageHeader>

      <pageMenu
        :type="type"
        :choose="choose"
        :params="params"
        :count="count"
        @change="changeList"
      >
      </pageMenu>

      <u-waterfall :value="list" ref="waterfall" idKey="id">
        <template v-slot:left="{ leftList }">
          <list
            :list="leftList"
            :isUser="isUser"
            @like="like"
            @longpress="longpress"
            :isWaterfall="true"
          ></list>
        </template>
        <template v-slot:right="{ rightList }">
          <list
            :list="rightList"
            :isUser="isUser"
            @like="like"
            @longpress="longpress"
            :isWaterfall="true"
          ></list
        ></template>
      </u-waterfall>

      <view class="noMore">{{ $t("home.noMore") }}~</view>

      <u-popup
        mode="bottom"
        v-model="showPopup"
        :z-index="121"
        border-radius="24"
        safe-area-inset-bottom
        :maskCloseAble="false"
      >
        <view class="popBox">
          <view class="popup-title">
            <view class="let"> {{ $t("common.more") }} </view>

            <i class="iconfont icon-close" @click="showPopup = false"></i>
          </view>

          <view
            class="popItem"
            v-if="getTopTit && parseInt(this.item.is_top) !== 1"
            @click="setTop"
          >
            <view class="let">
              <!-- <i class="iconfont"></i> -->
              <view class="text">{{ getTopTit.title }}</view>
            </view>
          </view>
          <view class="popItem" @click="remove">
            <view class="let">
              <!-- <i class="iconfont"></i> -->
              <view class="text">{{ $t("cart.delete") }}</view>
            </view>
          </view>
        </view>
      </u-popup>
    </template>

    <view class="addForm" @click="add" v-if="isUser">
      <i class="iconfont icon-video"></i>
      <view class="text">{{ $t("videoGoods.list.add") }}</view>
    </view>

    <!-- 全局过渡组件 -->
    <transitionPage></transitionPage>
  </view>
</template>

<script>
import videoClassify from "@/api/videoClassify";
import singleHeader from "@/components/diySystemPage/components/singleHeader/index.vue";
import pageHeader from "./components/page-header.vue";
import pageMenu from "./components/page-menu.vue";
import list from "../components/list.vue";

export default {
  components: {
    singleHeader,
    pageHeader,
    pageMenu,
    list,
  },

  data() {
    return {
      userInfo: null,
      list: [],
      id: undefined,
      userId: undefined,

      type: "0",
      choose: "-1",
      isEnd: false,
      page: 1,

      count: 0,

      opacity: 0,

      top: {
        0: {
          title: this.$t("videoGoods.userInfo.top"),
        },
        1: {
          title: this.$t("videoGoods.userInfo.cancelTop"),
        },
      },

      params: {
        items: [
          { id: "-1", name: this.$t("videoGoods.userInfo.dynamic") },
          { id: "1", name: this.$t("videoGoods.userInfo.likeIt") },
        ],

        tags: [
          { id: "0", name: this.$t("videoGoods.userInfo.all"), num: 0 },
          { id: "1", name: this.$t("videoGoods.userInfo.video"), num: 0 },
          { id: "2", name: this.$t("videoGoods.userInfo.img"), num: 0 },
        ],
      },

      showPopup: false,
      item: null,

      categoryList: [],
      isOpenAdd: false,
      isAuthor: false,
    };
  },

  computed: {
    getSetting() {
      return this.isOpenAdd && !this.isAuthor;
    },

    getTopTit() {
      if (!this.item) {
        return "";
      }
      let { item, top } = this,
        { is_top } = item;
      return top[is_top];
    },

    backgroundColor() {
      return "rgba(0,0,0,0)";
    },

    isUser() {
      return String(this.id) === String(this.userId);
    },

    isLike() {
      let { userInfo } = this;

      if (!userInfo || userInfo.is_focus === 0) {
        return [this.$t("videoGoods.list.follow"), "on"];
      }

      return [this.$t("videoGoods.list.checkedFollow"), ""];
    },
  },

  onLoad(opi) {
    try {
      const userInfo = uni.getStorageSync("userInfo");
      if (userInfo) {
        this.id = opi.id || userInfo.id;
        this.userId = userInfo.id;
      }
    } catch (e) {}

    this.videoAuditApplyConfig(() => {
      // 判断是否是作者 不是的话则去掉动态
      this.setSetting();
    });
  },

  onShow() {
    this.getUserInfo();
    this.getCategoryList();
  },

  methods: {
    setSetting() {
      this.$nextTick(() => {
        if (this.isUser && this.getSetting) {
          this.params.items.splice(0, 1);
          this.choose = "1";
        } else {
          this.params.items = [
            { id: "-1", name: this.$t("videoGoods.userInfo.dynamic") },
            { id: "1", name: this.$t("videoGoods.userInfo.likeIt") },
          ];

          this.choose = "-1";
        }

        this.clearData();
      });
    },

    videoAuditApplyConfig(fn) {
      videoClassify.videoAuditApplyConfig().then((res) => {
        if (res.code === 0) {
          this.isOpenAdd = res.data.is_author_audit;
          this.isAuthor = res.data.is_author;
          this.isApply = res.data.is_apply;

          if (fn) {
            fn();
          }
        }
      });
    },

    getCategoryList() {
      videoClassify.categoryList().then((res) => {
        if (res.code === 0) {
          this.categoryList = res.data;
        }
      });
    },

    clearData() {
      this.isEnd = false;
      this.page = 1;
      this.list = [];
      this.count = 0;
      this.$refs.waterfall.clear();

      this.videoGoodsUserVideoList();
    },

    longpress(item) {
      if (!this.isUser) {
        return;
      }

      // || this.choose === "1"

      this.item = item;
      this.showPopup = true;
    },

    like(item) {
      if (this.isUser) {
        return;
      }

      let { id, is_like } = item;
      // let { list } = this;
      // let newItem = list.find((el) => el.id === id);
      let el = this.$refs.waterfall;

      if (is_like === 0) {
        videoClassify
          .videoGoodsVote(
            {
              vl_id: id,
              type: "1",
            },
            false
          )
          .then((res) => {
            if (res.code === 0) {
              // this.$set(newItem, "is_like", 1);
              // this.$set(
              //   newItem,
              //   "like_count",
              //   parseInt(newItem.like_count) + 1
              // );

              el.modify(id, "is_like", 1);
              el.modify(id, "like_count", parseInt(item.like_count) + 1);
            }
          });
      } else {
        videoClassify
          .videoGoodsCancelVote(
            {
              vl_id: id,
              type: "1",
            },
            false
          )
          .then((res) => {
            if (res.code === 0) {
              // this.$set(newItem, "is_like", 0);
              // this.$set(
              //   newItem,
              //   "like_count",
              //   parseInt(newItem.like_count) - 1
              // );

              el.modify(id, "is_like", 0);
              el.modify(id, "like_count", parseInt(item.like_count) - 1);
            }
          });
      }
    },

    videoGoodsUserVideoList() {
      let { list: oldList, page, id: user_id, type, choose, count } = this,
        limit = 20,
        { tags } = this.params;

      videoClassify
        .videoGoodsUserVideoList({
          user_id,
          limit,
          page,
          choose,
          type,
        })
        .then((res) => {
          uni.stopPullDownRefresh();
          if (res.code === 0) {
            let { list, row_count, pic_count, video_count, all_count } =
                res.data,
              totalCount = parseInt(row_count) || 0,
              allCount = parseInt(all_count) || 0,
              picCount = parseInt(pic_count) || 0,
              videoCount = parseInt(video_count) || 0;

            this.$nextTick(() => {
              this.count = totalCount;

              tags[0].num = allCount;
              tags[1].num = videoCount;
              tags[2].num = picCount;
            });

            if (list.length) {
              oldList.push(...list);
              this.page = page + 1;
            }

            if (oldList.length >= count) {
              this.isEnd = true;
            }
          }
        })
        .catch(() => {
          uni.stopPullDownRefresh();
        });
    },

    changeList(key, value) {
      this[key] = value;

      this.clearData();
    },

    getUserInfo() {
      videoClassify
        .videoGoodsUserIndex({
          user_id: this.id,
        })
        .then((res) => {
          if (res.code === 0) {
            this.userInfo = res.data;
          }
        });
    },

    // 下拉刷新
    onPullDownRefresh() {
      this.getUserInfo();
      this.videoAuditApplyConfig(() => {
        // 判断是否是作者 不是的话则去掉动态
        this.setSetting();
      });
    },

    onPageScroll({ scrollTop }) {
      if (scrollTop >= 0 && scrollTop <= 100) {
        this.opacity = scrollTop / 100;
      }
    },

    // 滚动到底部
    onReachBottom() {
      if (this.isEnd) {
        return;
      }

      this.videoGoodsUserVideoList();
    },

    // 设置置顶
    setTop() {
      let { item, top } = this;

      this.$utils.showModal(
        this.$t("order.prompt"),
        this.$t("videoGoods.userInfo.is") +
          top[parseInt(item.is_top)].title +
          "?",
        true,
        () => {
          videoClassify
            .videoGoodsChangeTop({
              vl_id: item.id,
            })
            .then((res) => {
              if (res.code === 0) {
                this.clearData();

                this.showPopup = false;
                this.item = null;
                this.$utils.toast(res.msg);
              }
            });
        },
        () => {}
      );
    },

    // 删除自己作品
    remove() {
      let { item } = this;

      this.$utils.showModal(
        this.$t("order.prompt"),
        this.$t("videoGoods.userInfo.is") + this.$t("cart.delete") + "?",
        true,
        () => {
          videoClassify
            .videoGoodsUserDelete({
              id: item.id,
            })
            .then((res) => {
              if (res.code === 0) {
                this.clearData();
                this.$utils.toast(res.msg);
                this.showPopup = false;
              }
            });
        },
        () => {}
      );
    },

    // 关注和取消关注
    follow() {
      let { userInfo } = this,
        { is_focus, user_info } = userInfo,
        { id: user_id } = user_info;

      if (is_focus === 0) {
        videoClassify
          .videoGoodsFocus(
            {
              focus_user_id: user_id,
            },
            false
          )
          .then((res) => {
            if (res.code === 0) {
              this.$set(this.userInfo, "is_focus", 1);
              this.$utils.toast(res.msg);
            }
          });
      } else {
        videoClassify
          .videoGoodsCancelFocus(
            {
              user_id,
            },
            false
          )
          .then((res) => {
            if (res.code === 0) {
              this.$set(this.userInfo, "is_focus", 0);
              this.$utils.toast(res.msg);
            }
          });
      }
    },

    // 上传
    add() {
      let { categoryList, isOpenAdd, isAuthor, isApply } = this;

      if (isOpenAdd && !isAuthor) {
        if (isApply) {
          this.$utils.showModal(
            "提示",
            "已经提交审核请耐心等待！",
            false,
            () => {
              uni.navigateBack({
                delta: 1,
              });
            }
          );
          return;
        }
        this.$utils.toUrl("/videoGoods/register/index");
        return;
      }

      uni.showActionSheet({
        itemList: [
          this.$t("videoGoods.list.photograph"),
          this.$t("videoGoods.userInfo.video"),
        ],
        success: ({ tapIndex }) => {
          uni.navigateTo({
            url: `/videoGoods/add/index`,

            success(res) {
              res.eventChannel.emit("acceptDataFromOpenedPage", {
                type: tapIndex === 0 ? "2" : "1",
                categoryList: categoryList.filter((el) => el.id),
              });
            },
          });
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.user {
  background: #f2f2f2;
  min-height: 100vh;
}

.nav {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  z-index: 9;
  padding: 0 32rpx;
  transition: 0.3s all;

  .nav-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 44px;
  }

  image {
    width: 19rpx;
  }
}

.noMore {
  padding: 40rpx 0;
  font-size: 22rpx;
  text-align: center;
  color: #c1c1c1;
}

.box1 {
  height: 100vh;
}

.popBox {
  display: flex;
  flex-direction: column;
  padding: 0 36rpx;
}

.popup-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 26rpx 0;

  .let {
    font-size: 32rpx;
    color: #262626;
    font-weight: bold;
  }

  .iconfont {
    color: #262626;
  }
}

.popItem {
  display: flex;
  align-items: center;
  height: 80rpx;
  border-bottom: 1px solid #f8f8f8;

  &:last-of-type {
    border-bottom: 0;
  }

  .text {
    font-size: 28rpx;
    color: #262626;
  }
}

.addForm {
  position: fixed;
  right: 0;
  bottom: 148rpx;
  z-index: 6;
  display: flex;
  align-items: center;
  padding: 10rpx 14rpx 10rpx 20rpx;
  background: #f0250e;
  border-radius: 32px 0 0 32px;
  color: #fff;

  .iconfont {
    font-size: 40rpx;
  }

  .text {
    margin-left: 8rpx;
    font-size: 28rpx;
  }
}
</style>
